"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var fs = require("fs");
var path = require("path");
var unit_1 = require("../unit");
function defaultCallback(resolve, reject) {
    return function cb(err) {
        if (err) {
            reject(err);
        }
        resolve(true);
    };
}
/**
 * @param resolve
 * @param reject
 * @param _data 编码后的数据
 * */
function writeDefaultCallback(resolve, reject, _data) {
    return function cb(err) {
        if (err) {
            reject(err);
        }
        resolve(_data);
    };
}
var WriteFile = /** @class */ (function () {
    function WriteFile() {
        this._buffer = Buffer.alloc(0);
        this._offset = 0;
        //一次最多分配多少内存合适?
        this.MAX_BYTES_LENGTH = 1024;
    }
    WriteFile.prototype.stringToUnit8Array = function (text) {
        var _textArray = text.split('');
        // utf8中文字符占用3字节
        var BYTE_LENGTH = 3;
        var buf = Buffer.alloc(_textArray.length * BYTE_LENGTH);
        buf.write(text);
        return buf;
    };
    /**
     * @param fileName {string} 文件路径与文件名:./test1/a.txt
     * @param data 要写入到文件中的数据
     * @param callback
     * */
    WriteFile.prototype.write = function (fileName, data, callback) {
        if (callback === void 0) { callback = writeDefaultCallback; }
        fileName = path.resolve(fileName);
        console.log('write');
        var _data;
        if (!Buffer.isBuffer(data)) {
            _data = this.stringToUnit8Array(data);
        }
        console.log('write2');
        return new Promise(function (resolve, reject) {
            return fs.writeFile(fileName, _data, callback.call(null, resolve, reject, _data));
        });
    };
    WriteFile.unlinkFile = function (fileName) {
        fileName = path.resolve(fileName);
        if (unit_1.isExist(fileName)) {
            fs.unlink(fileName, function (err) {
                if (err) {
                    throw err;
                }
            });
        }
    };
    return WriteFile;
}());
exports.default = WriteFile;
